package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.selectOne(queryWrapper);   //使用mybatis-plus

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {

        System.out.println("当前线程的id："+Thread.currentThread().getId());

        //1、数据转换(建议将DTO转换为实体对象)
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //2.设置账号状态，1表示正常，0表示锁定
        employee.setStatus(StatusConstant.ENABLE); //定义的常量类，使得代码更加规范
        //3、新增员工设置默认密码再进行密码加密
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);
//        //设置创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //设置当前记录创建人和修改人
//
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //4、保存员工信息
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult page1(EmployeePageQueryDTO employeePageQueryDTO) {
        //采用mybatis-plus分页插件
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        //分页查询
        Page<Employee> page = new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> pageResult = null;
        //设置查询条件
        if (employeePageQueryDTO.getName()!= null && !employeePageQueryDTO.getName().equals("")) {
            //if语句作用是防止name为空字符串时，查询条件为空
            queryWrapper.like("name", employeePageQueryDTO.getName());
            pageResult = employeeMapper.selectPage(page, queryWrapper);

        }else {
            pageResult = employeeMapper.selectPage(page, null);
        }
        log.info("总记录数: " + pageResult.getTotal());

        return new PageResult(pageResult.getTotal(),pageResult.getRecords());
    }

    @Override
    public void startOrStop(Integer status, long id) {
        //1、根据id查询员工信息
        Employee employee = employeeMapper.selectById(id);
        //2、更新员工状态
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(employee);

    }

    @Override
    public void updateById(EmployeeDTO employeeDTO) {
        //数据转换(建议将DTO转换为实体对象)
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //更新员工信息
        employeeMapper.updateById(employee);
    }


}
